package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.domain.Pipeline;
import com.cavy.platform.server.domain.Stage;
import com.cavy.platform.server.repository.PipelineRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * 验证pipeline是否存在
 */
public class StageExistValidator implements ConstraintValidator<StageExist, StageExistData> {
    private PipelineRepository bean;

    @Override
    public void initialize(StageExist exist) {
        bean = BeansProvider.getBean(PipelineRepository.class);
    }

    @Override
    public boolean isValid(StageExistData dto, ConstraintValidatorContext context) {
        Pipeline pipeline = bean.find(dto.getWorkspace(), dto.getProjectName(), dto.getPipelineName());
        if (pipeline == null) {
            return true;
        }

        List<Stage> stageList = pipeline.getStageList();
        for (Stage stage : stageList) {
            if (stage.getName().equals(dto.getStageName())) {
                return true;
            }
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(dto.getStageFieldName()).addConstraintViolation();
        return false;
    }
}
